package com.corn.zk.lock;

import lombok.extern.slf4j.Slf4j;
import org.apache.zookeeper.KeeperException;

import java.io.IOException;

/**
 * @author : Jim Wu
 * @version 1.0
 * @function :
 * @since : 2022/7/12 16:29
 */

@Slf4j
public class DistributedLockTest {

    public static void main(String[] args) throws IOException, InterruptedException, KeeperException {
        DistributedLock lock1 = new DistributedLock("node1:2181");
        DistributedLock lock2 = new DistributedLock("node1:2181");

        new Thread(() -> {
            log.info("线程名称:{} 开始加锁, 时间戳:{}", Thread.currentThread().getName(), System.currentTimeMillis());
            try {
                lock1.lock();
                log.info("线程名称:{} 获取到锁开始直接业务, 时间戳:{}", Thread.currentThread().getName(), System.currentTimeMillis());
                Thread.sleep(5 * 1000);
                lock1.unlock();
                log.info("线程名称:{} 解锁", Thread.currentThread().getName());
            } catch (KeeperException | InterruptedException e) {
                e.printStackTrace();
            }

        }).start();


        new Thread(() -> {
            log.info("线程名称:{} 开始加锁, 时间戳:{}", Thread.currentThread().getName(), System.currentTimeMillis());
            try {
                lock2.lock();
                log.info("线程名称:{} 获取到锁开始直接业务, 时间戳:{}", Thread.currentThread().getName(), System.currentTimeMillis());
                Thread.sleep(3 * 1000);
                lock2.unlock();
                log.info("线程名称:{} 解锁", Thread.currentThread().getName());
            } catch (KeeperException | InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
    }
}
